package com.ba.redis;

import java.io.IOException;
import java.io.Serializable;
import java.util.Map;

import org.apache.commons.lang.SerializationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ba.utils.SerializeUtil;

import redis.clients.jedis.JedisCluster;

@Service("redisCacheStorage")
public class RedisClusterCacheStorageImpl{

    @Autowired
    private JedisCluster jedisCluster;

    public boolean set(String key, Object value, int exp) {
        return false;
    }

    public void set(Serializable key, Object value) {
      if (key != null && value != null) {
          jedisCluster.set(SerializeUtil.serialize(key), SerializeUtil.serialize(value));
      }
    }
    
    public void destory(){
      try {
          jedisCluster.close();
      } catch (IOException e) {
          e.printStackTrace();
      }
    }
    
    public Object get(Serializable sessionId) {
        byte[] bytes = null;
        if (sessionId != null) {
            bytes = jedisCluster.get(SerializeUtil.serialize(sessionId));
        }
        Object object = null;
        if(bytes != null){
            object = SerializationUtils.deserialize(bytes);
        }
        return object;
    }

    public void delete(Serializable key) {
        if(key != null){
            jedisCluster.del(SerializeUtil.serialize(key));
        }
    }
    
    public void update(Serializable key,Object value){ //jedis没有update接口？？
        if(key != null){
            delete(key);
            set(key, value);  
        }
    }

}
